<?php

namespace App\Trip\Plane\Variflight\Result;

class ComfortResult implements ComfortResultInterface
{
    private array $result;

    private array $flights;
    private array $condition;

    public function __construct(array $result, array $condition = [])
    {
        // 按城市+日期有data , 按航班号没有data 兼容处理
        $this->result = $result['data'] ?? $result;
        $this->init();
        $this->condition = $condition;
    }

    private function init(): void
    {
        foreach ($this->result as $one) {
            $flight                            = new QueryResultFlight($one);
            $this->flights[$one['FlightNo']][] = $flight?->getFlightInfo() ?: [];
        }
    }

    public function getLists(): array
    {
        return collect($this->result)
            ->map(fn($flight) => $this->findOneByFlightNo($flight['FlightNo']))->toArray();
    }

    public function findOneByFlightNo(string $flight_no): array
    {
        $matches = $this->flights[$flight_no] ?? [];
        if (empty($matches)) {
            return [];
        }

        // 根据条件筛选
        /**
         * @var $f
         */
        if (isset($this->condition['from_code'])) {
            $flight = collect($matches)->where('from_code', $this->condition['from_code'])->firstWhere('to_code', $this->condition['to_code']);
        } else {
            $flight = collect($matches)->first();
        }

        return $flight;
    }
}